<script lang="ts" setup>
import { ref, computed, Ref, onMounted, h, Fragment, reactive } from "vue";
import {
  PlusColumn,
  FieldValues,
  OptionsRow,
  useTable,
  TableFormRefRow,
  PlusTableInstance
} from "plus-pro-components";
import { useRoute, useRouter } from "vue-router";
defineOptions({
  name: "GoodAdd"
});
import { set } from "lodash-es";
import uploadApi from "@/api/upload";
import goodApi from "@/api/good";
import { useDictionary } from "@/utils/useDictionary";
import {
  ElButton,
  ElImage,
  ElUpload,
  UploadInstance,
  UploadRawFile,
  UploadUserFile,
  genFileId,
  ElMessage,
  FormInstance,
  ElTag
} from "element-plus";
import { fileToDataURL } from "@plus-pro-components/utils";
import FileManage from "@/components/FileManage/index.vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import file from "@/api/file";
import { log } from "console";
import { message } from "@/utils/message";
import { number } from "echarts";

const { tableData } = useTable();
const { GOOD, DICTIONARY } = useDictionary();

const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{
  domains: DomainItem[];
}>({
  domains: []
});

interface DomainItem {
  id: number;
  name: string;
  specValue: any[];
}

const removeDomain = async (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    console.log(item);
    await goodApi.specDelete({ ids: [item.id] });
    dynamicValidateForm.domains.splice(index, 1);
    setSkuDate();
  }
};

const addDomain = data => {
  dynamicValidateForm.domains.push(data);
};

const route = useRoute();
const router = useRouter();
const pageType = ref<string>("one");
const goodId = ref();
const isUpdate = computed(() => {
  return !!goodId.value;
});

// options推荐写法
const upDownOptions: Ref<OptionsRow[]> = ref([]);
const specTypeOptions: Ref<OptionsRow[]> = ref([]);
const goodTypeOptions: Ref<OptionsRow[]> = ref([]);
const getOptions = async () => {
  const STATUS = await DICTIONARY(GOOD.GOOD_UPDOWN_STATUS);
  upDownOptions.value = STATUS.data;

  const SPEC = await DICTIONARY(GOOD.GOOD_SKU_TYPE);
  specTypeOptions.value = SPEC.data;

  const GOODTYPE = await goodApi.goodTypeList();
  GOODTYPE.data.map(item => {
    item.label = item.name;
    item.value = item.id;
  });
  goodTypeOptions.value = GOODTYPE.data;
};
getOptions();

onMounted(async () => {
  if (route.query.id) {
    goodId.value = route.query.id;
    const GOOD = await goodApi.goodOne(goodId.value);
    stateOne.value = GOOD.data;
    fileList.value = [GOOD.data.img];
    if (GOOD.data.specType === 2) {
      dynamicValidateForm.domains = GOOD.data.spec;
      tableData.value = GOOD.data.sku;
      // setSkuDate();
    }
  }
});

// const url = ref("");
const dialogVisible = ref(false);
const visible = ref(false);
const visibleValues = ref<FieldValues>({});
const visibleColums: PlusColumn[] = [
  {
    label: "请输入规格名称",
    prop: "name"
  }
];
const visibleRules = {
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ]
};
const dialogItemVisible = ref(false);
const visibleItem = ref(false);
const visibleItemValues = ref<FieldValues>({});
const visibleItemleColums: PlusColumn[] = [
  {
    label: "请输入规格值",
    prop: "value"
  }
];
const visibleItemRules = {
  value: [
    {
      required: true,
      message: "请输入名称"
    }
  ]
};

const dialogImageUrl = ref("");
const uploadRef = ref<UploadInstance>();
const fileList = ref<UploadUserFile[]>([]);

const stateOne = ref<FieldValues>({
  status: 1,
  goodType: "",
  description: "",
  name: "",
  img: {},
  specType: 1,
  spec: [],
  price: 0,
  stock: 0,
  skuIds: [],
  specIds: []
});
const rules = {
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ],
  description: [
    {
      required: true,
      message: "请输入简介"
    }
  ],
  goodType: [
    {
      required: true,
      message: "请选择"
    }
  ],
  img: [
    {
      required: true,
      message: "上传图片"
    }
  ],
  status: [
    {
      required: true,
      message: "请选择"
    }
  ],
  specType: [
    {
      required: true,
      message: "请选择"
    }
  ],
  price: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          stateOne.value.specType === 1 &&
          (value === undefined || value === null || value === "")
        ) {
          callback(new Error("请输入"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  stock: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          stateOne.value.specType === 1 &&
          (value === undefined || value === null || value === "")
        ) {
          callback(new Error("请输入"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  skuIds: {
    required: true
  },
  specIds: {
    required: true
  }
};

const columns: PlusColumn[] = [
  {
    label: "商品名称",
    prop: "name"
  },
  {
    label: "商品简介",
    prop: "description",
    valueType: "textarea"
  },
  {
    label: "商品分类",
    prop: "goodType",
    valueType: "select",
    options: computed(() => goodTypeOptions.value)
  },
  {
    label: "封面图",
    prop: "img",
    valueType: "img",
    renderField(value, onChange) {
      // 自定义上传
      const handleHttpRequest = async ({ file, onError, onSuccess }: any) => {
        try {
          const formData = new FormData();
          formData.append("file", file);
          const result = await uploadApi.uploadImage(formData);
          onSuccess(
            Object.assign(file, {
              url: result.data.url,
              filename: result.data.filename
            })
          );
        } catch (error: any) {
          onError(error);
        }
        return file;
      };

      const handleRemove = (file, uploadFiles) => {
        fileList.value = uploadFiles;
        stateOne.value.img = null;
      };

      return h(Fragment, [
        h(
          ElUpload,
          {
            ref: uploadRef,
            action: "",
            limit: 1,
            httpRequest: handleHttpRequest,
            listType: "picture-card",
            fileList: fileList.value,
            showFileList: true,
            onChange: async (data: any) => {
              const value = await fileToDataURL(data.raw);

              // 手动调用 renderField 的onChange 回调把值传给表单
              if (data.status === "success") {
                console.log("onchange", data);
                fileList.value = [
                  {
                    name: data.raw.filename,
                    url: data.raw.url
                  }
                ];
                onChange({
                  name: data.raw.filename,
                  url: data.raw.url
                });
              }
            },
            onRemove: handleRemove,
            class: fileList.value.length >= 1 ? "upload-hidden" : "",
            onPreview: uploadFile => {
              dialogImageUrl.value = uploadFile.url!;
              dialogVisible.value = true;
            }
          },
          () =>
            h(IconifyIconOnline, {
              icon: "si:add-fill",
              width: "50px",
              height: "50px"
            })
        )
      ]);
    }
  },
  {
    label: "上架状态",
    prop: "status",
    valueType: "radio",
    options: computed(() => upDownOptions.value)
  },
  {
    label: "规格类型",
    prop: "specType",
    valueType: "radio",
    options: computed(() => specTypeOptions.value)
  },
  {
    label: "商品金额",
    prop: "price",
    valueType: "input-number",
    hideInForm: computed(() => stateOne.value.specType !== 1),
    formItemProps: {
      required: true
    }
  },
  {
    label: "商品库存",
    prop: "stock",
    valueType: "input-number",
    hideInForm: computed(() => stateOne.value.specType !== 1),
    formItemProps: {
      required: true
    }
  },
  {
    label: "规格",
    prop: "specIds",
    hideInForm: true,
    formItemProps: {
      required: false
    }
  },
  {
    label: "规格",
    prop: "skuIds",
    hideInForm: computed(() => stateOne.value.specType !== 2),
    formItemProps: {
      required: false
    }
  }
];

const handleChange = (values: FieldValues, prop: PlusColumn) => {
  console.log(values, prop, "change");
};
const handleSubmit = async (values: FieldValues) => {
  if (isUpdate.value) {
    try {
      if (stateOne.value.specType === 1) {
        const UPDAT = await goodApi.goodUpdate(
          Object.assign({}, values, { id: goodId.value })
        );
        ElMessage({
          type: "success",
          message: "修改成功"
        });
        router.push({
          name: "GoodList"
        });
      } else {
        try {
          if (tableData.value.length > 0) {
            const da = await Promise.all(
              plusTableInstance.value.formRefs[0]?.map(
                (item: TableFormRefRow) => {
                  console.log(item);
                  return item.formInstance.value?.validate();
                }
              )
            );
            console.log(da, "da");
          }
          const UPDAT = await goodApi.goodUpdate(
            Object.assign({}, values, {
              id: goodId.value,
              ...(tableData.value && { sku: tableData.value })
            })
          );
          ElMessage({
            type: "success",
            message: "修改成功"
          });
        } catch (errors: any) {
          console.log(errors, "errors");
          ElMessage.closeAll();
          const values: any[] = Object.values(errors);
          ElMessage.warning(
            values[0]?.[0]?.message || "请完整填写表单并再次提交！"
          );
        }
      }
    } catch (error) {}
  } else {
    try {
      if (stateOne.value.specType === 1) {
        const ADD = await goodApi.goodCreate(values);
        ElMessage({
          type: "success",
          message: "添加成功"
        });
        router.push({
          name: "GoodList"
        });
      } else {
        const ADD = await goodApi.goodCreate(values);
        goodId.value = ADD.data;
        ElMessage({
          type: "success",
          message: "保存成功"
        });
      }
    } catch (error) {}
  }
};
const handleSubmitError = (err: any) => {
  console.log(err, "err");
};
const handleReset = () => {
  console.log("handleReset");
};
function handelevisible() {
  if (!goodId.value) {
    return ElMessage({
      type: "info",
      message: "请先提交基础商品信息"
    });
  }
  visible.value = true;
}
async function visibleConfirm(values: FieldValues) {
  const ADD = await goodApi.specCreate(
    Object.assign({}, values, { goodId: goodId.value })
  );
  addDomain(Object.assign({}, values, { id: ADD.data, specValue: [] }));
  visibleValues.value = {
    name: ""
  };
  visible.value = false;
  setSkuDate();
}
const selectSpecId = ref();
function addSpecValue(id: number) {
  selectSpecId.value = id;
  visibleItem.value = true;
}

async function visibleItemConfirm(values: FieldValues) {
  const ADD = await goodApi.specValueCreate(
    Object.assign({}, values, { id: selectSpecId.value })
  );
  const obj = dynamicValidateForm.domains.find(
    item => item.id === selectSpecId.value
  );
  if (obj) {
    obj.specValue.push({
      id: ADD.data,
      value: values.value
    });
  }
  visibleItemValues.value = {
    value: ""
  };
  visibleItem.value = false;
  setSkuDate();
}

async function tagDel(id: number, item) {
  const obj = dynamicValidateForm.domains.find(items => items.id === id);
  console.log(obj);

  if (obj) {
    await goodApi.specValueDelete({ ids: [item.id] });
    const index = obj.specValue.indexOf(item);
    obj.specValue.splice(index, 1);
    setSkuDate();
  }
}
const plusTableInstance = ref();
const skuTableConfig: PlusColumn[] = [
  // {
  //   label: "图片",
  //   prop: "img",
  //   valueType: "img",
  //   editable: false,
  //   formProps: {
  //     // 添加校验
  //     rules: {
  //       img: [
  //         {
  //           required: true,
  //           message: "请上传图片"
  //         }
  //       ]
  //     }
  //   }
  // },
  {
    label: "id",
    prop: "id",
    editable: false,
    hideInTable: true
  },
  {
    label: "规格",
    prop: "specCombination",
    editable: false,
    renderHTML: value => {
      return `<div>${Object.values(value)}</div>`;
    }
  },
  {
    label: "价格",
    prop: "price",
    valueType: "input-number",
    fieldProps: {
      min: 0
    },
    formProps: {
      // 添加校验
      rules: {
        price: [
          {
            required: true,
            message: "请输入价格"
          }
        ]
      }
    }
  },
  {
    label: "库存",
    prop: "stock",
    valueType: "input-number",
    fieldProps: {
      min: 0,
      precision: 0
    },
    formProps: {
      // 添加校验
      rules: {
        stock: [
          {
            required: true,
            message: "请输入库存"
          }
        ]
      }
    }
  }
];

function setSkuDate() {
  let data = dynamicValidateForm.domains
    .filter(item => item.specValue && item.specValue.length > 0)
    .map(item => item.specValue);

  const list = generateSkuCombinations(data);
  const newarr = list.map(item => {
    const arr = item.reduce((accumulator, currentValue) => {
      return Object.assign({}, accumulator, {
        [currentValue.id]: currentValue.value
      });
    }, {});
    return {
      // img: "",
      specCombination: arr,
      price: null,
      stock: null,
      id: null
    };
  });
  tableData.value = newarr;
}

/**
 * 生成 SKU 参数组合
 * @param {Array} skuOptions - 嵌套数组，每个数组包含一组规格选项
 * @returns {Array} 所有 SKU 参数组合的数组
 */
function generateSkuCombinations(skuOptions) {
  if (!skuOptions || skuOptions.length === 0) return [];

  // 笛卡尔积逻辑
  const combine = (options, index = 0, current = []) => {
    if (index === options.length) {
      return [current]; // 返回组合结果
    }

    const result = [];
    options[index].forEach(option => {
      result.push(...combine(options, index + 1, [...current, option]));
    });
    return result;
  };

  return combine(skuOptions);
}
const formChange = ({ value, prop, index }) => {
  // 同步表单数据到表格
  set(tableData.value[index], prop, value);
  console.log(tableData.value, "tableData.value");
};
</script>
<template>
  <ElCard shadow="never">
    <!-- <template #header>
      <h5>{{ isUpdate ? "编辑商品" : "添加商品" }}</h5>
    </template> -->
    <ElTabs v-model="pageType" class="md:mr-[50%]">
      <ElTabPane label="基本数据" name="one">
        <PlusForm
          v-model="stateOne"
          :columns="columns"
          :rules="rules"
          :row-props="{ gutter: 20 }"
          labelPosition="left"
          labelWidth="auto"
          @change="handleChange"
          @submit="handleSubmit"
          @submit-error="handleSubmitError"
          @reset="handleReset"
        >
          <template #plus-field-skuIds>
            <el-form
              ref="formRef"
              :model="dynamicValidateForm"
              label-width="auto"
              class="!w-full"
            >
              <ElFormItem>
                <ElButton type="success" @click="handelevisible"
                  >新增规格</ElButton
                >
              </ElFormItem>
              <el-form-item
                v-for="(domain, index) in dynamicValidateForm.domains"
                :key="index"
                :prop="'domains.' + index + '.value'"
                :rules="{
                  required: false,
                  message: 'domain can not be null',
                  trigger: 'blur'
                }"
                class="my-2 w-full"
              >
                <div class="flex items-center bg-[#f5f5f5] p-3 w-full">
                  <div>
                    <div class="flex whitespace-nowrap">
                      <span class="mr-2">规格名:</span>
                      <el-input v-model="domain.name" readonly />
                    </div>
                    <div class="flex gap-2 items-center whitespace-nowrap mt-2">
                      <span>规格值:</span>
                      <template
                        v-for="(item, indexs) in domain.specValue"
                        :key="indexs"
                      >
                        <ElTag
                          closable
                          type="primary"
                          @close="tagDel(domain.id, item)"
                          >{{ item.value }}</ElTag
                        >
                      </template>
                      <ElButton size="small" @click="addSpecValue(domain.id)">
                        <template #icon>
                          <IconifyIconOnline
                            icon="material-symbols-light:add"
                          />
                        </template>
                        添加
                      </ElButton>
                    </div>
                  </div>
                  <el-button
                    class="mt-2 ml-auto !text-red-600"
                    type="text"
                    @click.prevent="removeDomain(domain)"
                  >
                    删除规格
                  </el-button>
                </div>
              </el-form-item>
              <!-- <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)"
                  >Submit</el-button
                >
                <el-button @click="addDomain">New domain</el-button>
                <el-button @click="resetForm(formRef)">Reset</el-button>
              </el-form-item> -->
              <ElFormItem class="my-2">
                <div class="w-full">
                  <PlusTable
                    ref="plusTableInstance"
                    editable
                    hasIndexColumn
                    :index-table-column-props="{
                      label: '序号',
                      width: 80
                    }"
                    :columns="skuTableConfig"
                    :table-data="tableData"
                    class="w-full"
                    @formChange="formChange"
                  />
                </div>
              </ElFormItem>
            </el-form>
          </template>
        </PlusForm>
      </ElTabPane>
    </ElTabs>
    <ElDialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </ElDialog>
    <PlusDialogForm
      v-model="visibleValues"
      v-model:visible="visible"
      title="添加规格"
      :form="{
        columns: visibleColums,
        rules: visibleRules,
        labelWidth: 'auto',
        labelPosition: 'top'
      }"
      class="!w-[95%] md:!w-[50%]"
      @confirm="visibleConfirm"
    />

    <PlusDialogForm
      v-model="visibleItemValues"
      v-model:visible="visibleItem"
      title="添加规格值"
      :form="{
        columns: visibleItemleColums,
        rules: visibleItemRules,
        labelWidth: 'auto',
        labelPosition: 'top'
      }"
      class="!w-[95%] md:!w-[50%]"
      @confirm="visibleItemConfirm"
    />
  </ElCard>
</template>
<style>
.upload-hidden .el-upload {
  display: none;
}
</style>
